<!DOCTYPE html>





<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-sunset.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-sunset.png?v=7.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-sunset.png?v=7.4.0">
  <link rel="mask-icon" href="/images/logo-sunset.svg?v=7.4.0" color="#222">

<link rel="stylesheet" href="/css/main.css?v=7.4.0">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.7.0">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.4.0',
    exturl: false,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: '',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    translation: {
      copy_button: '复制',
      copy_success: '复制成功',
      copy_failure: '复制失败'
    },
    sidebarPadding: 40
  };
</script>

  <meta name="description" content="在我们实际运维和服务器性能测试的时候，需要知道CPU的使用情况，以下引用《Linux Shell脚本攻略》的文章，介绍一下，如果列出1小时内占用CPU最多的10个进程。CPU时间是一项重要的资源，有事我们需要跟踪某个时期内占用CPU周期最多的进程。在普通的桌面系统上，CPU处于高负荷状态也许不会引发问题，但是对于需要处理大量请求的服务器来说，CPU是极其重要的资源。通过监视某个时期内CPU的使用情">
<meta name="keywords" content="技术分享">
<meta property="og:type" content="article">
<meta property="og:title" content="列出1小时内占用CPU最多的10个进程">
<meta property="og:url" content="http://yoursite.com/2019/10/01/列出1小时内占用CPU最多的10个进程/index.html">
<meta property="og:site_name" content="志泳的博客-学习、分享、成长">
<meta property="og:description" content="在我们实际运维和服务器性能测试的时候，需要知道CPU的使用情况，以下引用《Linux Shell脚本攻略》的文章，介绍一下，如果列出1小时内占用CPU最多的10个进程。CPU时间是一项重要的资源，有事我们需要跟踪某个时期内占用CPU周期最多的进程。在普通的桌面系统上，CPU处于高负荷状态也许不会引发问题，但是对于需要处理大量请求的服务器来说，CPU是极其重要的资源。通过监视某个时期内CPU的使用情">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-10-23T15:28:02.987Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="列出1小时内占用CPU最多的10个进程">
<meta name="twitter:description" content="在我们实际运维和服务器性能测试的时候，需要知道CPU的使用情况，以下引用《Linux Shell脚本攻略》的文章，介绍一下，如果列出1小时内占用CPU最多的10个进程。CPU时间是一项重要的资源，有事我们需要跟踪某个时期内占用CPU周期最多的进程。在普通的桌面系统上，CPU处于高负荷状态也许不会引发问题，但是对于需要处理大量请求的服务器来说，CPU是极其重要的资源。通过监视某个时期内CPU的使用情">
  <link rel="canonical" href="http://yoursite.com/2019/10/01/列出1小时内占用CPU最多的10个进程/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>列出1小时内占用CPU最多的10个进程 | 志泳的博客-学习、分享、成长</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?aff336890e85bc8e76e40e879cca6bf8";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">
  <div class="container use-motion">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">志泳的博客-学习、分享、成长</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
      
      
      
        
        <li class="menu-item menu-item-home">
      
    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
      
      
      
        
        <li class="menu-item menu-item-archives">
      
    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
            

          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
      <article itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block post">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/10/01/列出1小时内占用CPU最多的10个进程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jimmy Wong">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="志泳的博客-学习、分享、成长">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">列出1小时内占用CPU最多的10个进程

          
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              
                
              

              <time title="创建时间：2019-10-01 17:42:21" itemprop="dateCreated datePublished" datetime="2019-10-01T17:42:21+00:00">2019-10-01</time>
            </span>
          
            

            
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-10-23 15:28:02" itemprop="dateModified" datetime="2019-10-23T15:28:02+00:00">2019-10-23</time>
              </span>
            
          

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在我们实际运维和服务器性能测试的时候，需要知道CPU的使用情况，以下引用《Linux Shell脚本攻略》的文章，介绍一下，如果列出1小时内占用CPU最多的10个进程。</p><p>CPU时间是一项重要的资源，有事我们需要跟踪某个时期内占用CPU周期最多的进程。在普通的桌面系统上，CPU处于高负荷状态也许不会引发问题，但是对于需要处理大量请求的服务器来说，CPU是极其重要的资源。通过监视某个时期内CPU的使用情况，我们可以找出长期占用CPU的进程并进行优化，或是调试其他问题。今天分享一个有关进程监视和日志记录的命令。</p><h1 id="新手上路"><a href="#新手上路" class="headerlink" title="新手上路"></a>新手上路</h1><p>ps命令用于收集系统中进程的详细信息。这些信息包括CPU使用情况、正在执行的命令、内存使用、进程状态等。记录在一个小时内占用郭CPU进程，然后通过恰当地运用ps以及文本处理就可以找出占用CPU最多的10个进程。</p><a id="more"></a>


<h1 id="实战演练"><a href="#实战演练" class="headerlink" title="实战演练"></a>实战演练</h1><p>让我们看看用于监视并计算一小时内CPU使用情况的shell脚本：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash</span><br><span class="line">#文件名:pcpu_usage.sh</span><br><span class="line">#用途:计算1个小时内进程的CPU占用情况</span><br><span class="line"></span><br><span class="line">SECS=3600</span><br><span class="line">UNIT_TIME=60</span><br><span class="line"></span><br><span class="line">#将SECS更改陈需要进行监视的总秒数</span><br><span class="line">#UNIT_TIME是取样的时间间隔，单位是秒</span><br><span class="line"></span><br><span class="line">STEPS=$(( $SECS / $UNIT_TIME ))</span><br><span class="line">echo Watching CPU usage ...;</span><br><span class="line">for((i=0;i&lt;STEPS;i++))</span><br><span class="line">do</span><br><span class="line">  ps -eo comm,pcpu | tail -n +2 &gt;&gt; /tmp/cpu_usage.$$</span><br><span class="line">  sleep $UNIT_TIME</span><br><span class="line">done</span><br><span class="line"></span><br><span class="line">echo</span><br><span class="line">echo CPU eaters :</span><br><span class="line"></span><br><span class="line">cat /tmp/cpu_usage.$$ | \</span><br><span class="line">awk &apos;</span><br><span class="line">&#123; process[$1]+=$2; &#125;</span><br><span class="line">END&#123;</span><br><span class="line">  for(i in process)</span><br><span class="line">  &#123;</span><br><span class="line">    printf(&quot;%-20s %s \n&quot;,i, process[i]) ;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;&apos; | sort -nrk 2 | head</span><br><span class="line">rm  /tmp/cpu_usage.$$</span><br><span class="line">#删除临时日志文件</span><br></pre></td></tr></table></figure>

<h1 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h1><p>在上面的脚本中，主要的输入源是  ps -eo comm,pcpu， 其中comm 表示命令名 (command name), pcpu 表示CPU使用率(CPU usage in precent)。该命令输出所有进程名及CPU使用率。每个进程对应一行输出。因为需要监视一小时内CPU的使用情况，所以我们得在一个每次迭代时间为60秒的for循环中不停地用  ps -eo comm.pcpu| tail -n +2来获取CPU的使用统计数据，并将这些数据添加到文件 /tmp/cpu_usage.$$中。60喵的迭代时间通过sleep 60来提供。这就使得每一分钟执行一次ps。<br>tail -n +2 用来将输出中的头部和COMMAND %CPU剥除。<br>cpu_usage.$$中的$$标识当前脚本的进程ID。假设进程ID为1345，那么在脚本执行时他会被替换位 /tmp/cpu_usage.1345。因为这适应临时文件，所以我们把它放到/tmp中。<br>统计文件在1小时后就准备妥当，文件包含60项，分别对应每分钟的进程状态。然后用awk 求出每个进程中的CPU使用情况，我们用了一个关联数组来统计CPU使用情况。其中进程名作为数组索引，最后根据总得CPU使用情况依数值，逆序排序，并通过head获取前10项。</p>

    </div>

    
    
    
        
      

      <footer class="post-footer">
          
            
          
          <div class="post-tags">
            
              <a href="/tags/技术分享/" rel="tag"># 技术分享</a>
            
          </div>
        

        

          <div class="post-nav">
            <div class="post-nav-next post-nav-item">
              
                <a href="/2019/09/26/手写一个永不重复的发号机/" rel="next" title="手写一个规则可配置的高并发的发号机">
                  <i class="fa fa-chevron-left"></i> 手写一个规则可配置的高并发的发号机
                </a>
              
            </div>

            <span class="post-nav-divider"></span>

            <div class="post-nav-prev post-nav-item">
              
                <a href="/2019/10/02/开发管理-git管理规范/" rel="prev" title="开发管理-GIT分支管理">
                  开发管理-GIT分支管理 <i class="fa fa-chevron-right"></i>
                </a>
              
            </div>
          </div>
        
      </footer>
    
  </div>
  
  
  
  </article>

  </div>


          </div>
          
    
    <div class="comments" id="gitalk-container"></div>
  

        </div>
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
        
        
        
        
      

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#新手上路"><span class="nav-number">1.</span> <span class="nav-text">新手上路</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#实战演练"><span class="nav-number">2.</span> <span class="nav-text">实战演练</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#工作原理"><span class="nav-number">3.</span> <span class="nav-text">工作原理</span></a></li></ol></div>
        
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Jimmy Wong</p>
  <div class="site-description" itemprop="description"></div>
</div>
  <nav class="site-state motion-element">
      <div class="site-state-item site-state-posts">
        
          <a href="/archives/">
        
          <span class="site-state-item-count">12</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
    
      
      
      <div class="site-state-item site-state-tags">
        
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span>
        
      </div>
    
  </nav>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jimmy Wong</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.9.0</div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.4.0</div>

        












        
      </div>
    </footer>
  </div>

  


  <script src="/lib/anime.min.js?v=3.1.0"></script>
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
<script src="/js/utils.js?v=7.4.0"></script><script src="/js/motion.js?v=7.4.0"></script>
<script src="/js/schemes/pisces.js?v=7.4.0"></script>

<script src="/js/next-boot.js?v=7.4.0"></script>



  





















  

  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID: '1e03a8c2c942a007aa2d',
      clientSecret: 'c13db1d348fcbb2f0151ed1472c95119b9b34445',
      repo: 'blog-comment',
      owner: 'hzy2009',
      admin: ['hzy2009'],
      id: 'be5b96578c33f79845bbdead6ee8c514',
        language: 'zh-CN',
      
      distractionFreeMode: 'true'
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
</script>

</body>
</html>
